<template>
  <div class="listgoods">
    <div class="product_s">
      <el-input v-model="productInput" placeholder="商品名" />
      <el-button type="primary" :icon="Search" @click="suouser()">搜索</el-button>
      <el-button type="info" @click="dialogVisibleclick()">添加</el-button>
    </div>
    <el-table :data="productTableData" style="width: 100%">
      <el-table-column prop="id" label="序号" />
      <el-table-column prop="goodsBigLogo" label="缩略图">
        <template #default="scope">
          <!-- {{scope.row.goodsBigLogo}} -->
          <!-- <img :src="'http://lqgapidemo.quechao.xyz/images/upload/rootswiper/'+scope.row.goodsSmallLogo" alt="" width="100" height="100" /> -->
            <el-image
                  style="width: 100px; height: 100px"
                  :src="dz+scope.row.goodsSmallLogo"
                  :fit="fit"
             ></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="goodsName" label="商品名" />
      <el-table-column prop="goodsPrice" label="价格" />
      <el-table-column prop="goodsWeight" label="重量" />
      <el-table-column prop="goodsNumber" label="数量" />
      <el-table-column prop="goodsStatus" label="上架/下架">
        <template #default="scope">
          <el-switch
            v-model="scope.row.goodsStatus"
            @change="changgoodsStatus($event, scope.row.id)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="isLayout" label="是否首页">
        <template #default="scope">
          <el-switch
            v-model="scope.row.isLayout"
            :active-value="1"
            :inactive-value="2"
            @change="changisLayout($event, scope.row.id)"
          />
        </template>
      </el-table-column>

      <el-table-column prop="createdAt" label="发布时间" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-dropdown color="#409EFF">
            <span class="el-dropdown-link">
              Dropdown List
              <el-icon class="el-icon--right">
                <arrow-down />
              </el-icon>
            </span>
            <template #dropdown split-button type="primary">
              <el-dropdown-menu>
                <el-dropdown-item @click="EdictProduct(scope.row)"
                  >基本编辑</el-dropdown-item
                >
                <el-dropdown-item @click="EdictProductImg(scope.row)"
                  >编辑头像</el-dropdown-item
                >
                <el-dropdown-item @click="EdictProducText(scope.row)"
                  >编辑详情</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <div class="page">
      <el-pagination
        background
        v-model="page.pageNo"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="num"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>

    <el-dialog v-model="dialogVisible" width="30%">
      <el-form
        label-position="Left"
        label-width="100px"
        :model="userUpdateRole"
        style="max-width: 460px"
      >
        <el-form-item label="商品名:">
          <el-input v-model="proEdit.goodsName"></el-input>
        </el-form-item>

        <el-form-item label="价格:">
          <el-input v-model="proEdit.goodsPrice"></el-input>
        </el-form-item>
        <el-form-item label="库存:">
          <el-input v-model="proEdit.goodsNumber"></el-input>
        </el-form-item>
        <el-form-item label="重量(克):">
          <el-input v-model="proEdit.goodsWeight"></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="dialogVisibleEdite()">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog v-model="dialogImgVisible" width="30%">
      <!-- <el-upload
        class="avatar-uploader"
        :headers="headersCofing"
        :data="{'folder': 'product','isResize': '2'}"
        name="file"
        :limit="1"
        action="http://lqgapidemo.quechao.xyz/upload/image"
        :auto-upload="true"
        list-type="picture-card"
        :on-success="handleAvatarSuccess"
      >
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon"><plus /></el-icon>
      </el-upload> -->

              <el-upload
          class="avatar-uploader"
          :headers="headersCofing"
          action="https://lqshuige.top:9000/upload/image"
          :show-file-list="false"
          :limit="1"
            name="file"
          :on-success="handleAvatarSuccess"
           :before-upload="beforeAvatarUpload"
         :data="{'folder': 'prd'}"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><plus /></el-icon>
        </el-upload>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog v-model="dialogTextVisible" width="30%">
      <quill-editor ref="myQuillEditor" v-model="content" :options="editorOption" />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogTextVisible = false">取消</el-button>
          <el-button type="primary" @click="dialogVisibleTextEdite()">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {
  onMounted,
  getCurrentInstance,
  ref
} from "vue";
import { ArrowDown } from "@element-plus/icons-vue";
import {
  Edit,
  Share,
  Delete,
  Search,
  Upload,
  Tools,
  Plus,
} from "@element-plus/icons-vue";
// import { request } from "@/network/request";
import httpRequest from '../service';
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import type {
  UploadFile,
  ElUploadProgressEvent,
  ElFile,
} from "element-plus/es/components/upload/src/upload.type";
const content = ref("");
const productTableData = ref("");
const dialogVisible = ref(false);
const dialogImgVisible = ref(false);
const productInput = ref("");
const search = ref("");
const proEdit = ref({});
const imageUrl = ref("");
const headersCofing = ref<any>("");
const dialogTextVisible = ref(false);
let proImgId = ref(0);
let num = ref<Number>(0);
 let dz= ref('https://lqshuige.top:9000/images/upload/prd/')
let page = {
  pageNo: 1,
  pageSize: 20,
  goodsName: productInput.value,
};

const router = useRouter();
onMounted(() => {
  let token = window.sessionStorage.getItem("token");
  headersCofing.value = { Authorization: token };
  getProducts();
});
const beforeAvatarUpload =(file: ElFile) =>{
            const isJPG = file.type === 'image/jpeg'
            const isLt2M = file.size / 1024 / 1024 < 2

            if (!isJPG) {
              ElMessage.error('Avatar picture must be JPG format!')
            }
            if (!isLt2M) {
              ElMessage.error('Avatar picture size can not exceed 2MB!')
            }
            return isJPG && isLt2M
}
// 添加详细
const dialogVisibleclick = () => {
  router.push("/goodsadd");
};

// 编辑详细
const EdictProducText = () => {
  dialogTextVisible.value = true;
};

// 富文本
// const dialogVisibleTextEdite = () => {
//   console.log(1);

// }
const handleAvatarSuccess = (res: any, file: UploadFile) => {
  console.log(res);
  
  let {path} = res.data

  httpRequest.request({url:'/goods/updgoods' ,method: 'post',data:{goodsSmallLogo:path,id:proImgId.value}}).then(res=>{
    dialogImgVisible.value = false;
      ElMessage({
        message: "修改成功",
        type: "success",
      });
      suouser();
  })
  
  imageUrl.value = URL.createObjectURL(file.raw);
};
// 分页
const handleSizeChange = (pageSize: number | string) => {
  page.pageNo = 1;
  page.pageSize = Number(pageSize);
  getProductAll();
};
const handleCurrentChange = () => {
  getProductAll();
};

// 编辑头像
const EdictProductImg = (pro:any) => {
  dialogImgVisible.value = true;
  proImgId.value = pro.id;

};

// 基本编辑(1.1)
const EdictProduct = (pro:any) => {
  dialogVisible.value = true;
  proEdit.value = { ...pro };
};

// 基本编辑(1.2)
const dialogVisibleEdite = () => {
  dialogVisible.value = false;
  httpRequest.request({ url: "/goods/updgoods" ,method: 'post', data: proEdit.value }).then(
    (res: any) => {
      ElMessage({
        message: "修改成功",
        type: "success",
      });
       proImgId.value =''
      suouser();
    }
  );
};

// 搜索
const suouser = () => {
  // console.log(userInput.value);
  page.pageNo = 1;
  getProductAll();
};

// 管上架状态
const changgoodsStatus = (val:any, proId:any) => {
  let pro = {
    id: 0,
    chkStatus: "",
  };
  pro.id = proId;
  pro.chkStatus = val;
  // update({ axios, url: "api/goods/updgoods", data: user }).then((res: any) => {
  //   ElMessage({
  //     message: "修改成功",
  //     type: "success",
  //   });
  // });

  // getProducts();
};

// 是否首页
const changisLayout = (val:any, proId:any) => {
  let pro = {
    id: 0,
    isLayout: "",
  };
  pro.id = proId;
  pro.isLayout = val;

  httpRequest.request({ url: "/goods/updgoods" ,method: 'post', data: pro }).then((res: any) => {
    ElMessage({
      message: "修改成功",
      type: "success",
    });
  });

  getProducts();
};

const getProductAll = () => {
  httpRequest.request({ url: "/goods/listgoods" ,method: 'post', data: page }).then((res: any) => {
    // productTableData.value = res.data.data.rows;
    let {
      data: { count, rows },
    } = res;
    productTableData.value = rows;
    num.value = count;
  });
};

// 获取所有商品
const getProducts = () => {
  getProductAll();
};


</script>

<style lang="less" scope>

  .listgoods{
    padding: 20px;
  }
.product_s {
  display: flex;
  margin-bottom: 10px;
  .el-input {
    width: 240px;
    // margin-left:20px;
    margin-right: 20px;
  }

  .el-button {
    margin-left: 20px;
  }
}

.page {
  margin-top: 30px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
